<?php
/**
 * CK 快速开发框架
 * User: Clake
 * Date: 15/6/2
 * Time: 03:12
 */

/**
 * 快速获取配置文件值
 * @param string $key <节点路径>
 * @param string $conf_name <配置文件名>
 *
 * @return mixed
 */
function C($key=null,$conf_name=null) {
    if (is_null($conf_name)) {
        return \CK\Core\Config::inst(CK_DEF_CONF)->get($key);
    } else {
        return \CK\Core\Config::inst($conf_name)->get($key);
    }
}

/**
 * 得到表操作对像
 * @param $table_name
 *
 * @return \CK\Database\Table
 */
function T($table_name) {
    return \CK\Database\DBA::inst()->getTable($table_name);
}

/**
 * 取得GET,POST数据
 * @param string $path get.key,post.key
 *
 * @return null
 */
function R($path) {
    $arr = explode('.',$path);
    if (count($arr) > 0) {
        $type = strtolower($arr[0]);
        $key = $arr[1];
    } else {
        $type = 'request';
        $key = $path;
    }

    switch ($type) {
        case 'get':
            if ($key === '*') {
                return $_GET;
            } else {
                return isset($_GET[$key]) ? $_GET[$key] : null;
            }
        case 'post':
            if ($key === '*') {
                return $_POST;
            }
            return isset($_POST[$key]) ? $_POST[$key] : null;
        case 'request':
            if ($key === '*') {
                return $_REQUEST;
            }
            return isset($_REQUEST[$key]) ? $_REQUEST[$key] : null;
        default:
            return null;
    }
}

/**
 * 格式化时间戳为字符串时间
 * @param        $format
 * @param        $time_stamp
 * @param string $def
 *
 * @return bool|string
 */
function c_date($format,$time_stamp,$def='') {
    if (intval($time_stamp) > 0) {
        return date($format,$time_stamp);
    } else {
        return $def;
    }
}

/**
 * 得到当前请求的IP
 * @return string
 */
function get_ip() {
    $unknown = 'unknown';
    if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] ) && $_SERVER ['HTTP_X_FORWARDED_FOR'] && strcasecmp ( $_SERVER ['HTTP_X_FORWARDED_FOR'], $unknown )) {
        $ip = $_SERVER ['HTTP_X_FORWARDED_FOR'];
    } elseif (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], $unknown )) {
        $ip = $_SERVER ['REMOTE_ADDR'];
    }
    /*
     * 处理多层代理的情况 或者使用正则方式：$ip = preg_match("/[\d\.] {7,15}/", $ip, $matches) ? $matches[0] : $unknown;
    */
    if (false !== strpos ( $ip, ',' ))
        $ip = reset ( explode ( ',', $ip ) );
    return trim ( $ip );
}

/**
 * 引入文件类
 *
 * @param string $path core.sss.sss
 * @param string $main_dir
 *
 */
function import($path,$main_dir='./'){
    static $imports = [];
    $path = $main_dir.str_replace(".","/",$path);

    if(substr($path,-1) != "*") {
        $path .= ".class.php";
        if (!is_file($path)) {
            $path = str_replace('.class.php', '.php', $path);
        }
    }

    foreach(glob($path) as $file){
        if(is_dir($file)) import($file.".*");
        if (isset($imports[$file])) continue;
        if(substr($file,-10) != ".class.php" && substr($file,-4) != ".php") continue;
        require $file;
        $imports[$file] = true;
    }
}

/**
 * 判断数组是否为 KEY/VALUE 键值对
 * @param $arr
 *
 * @return bool
 */
function is_assoc ($arr) {
    return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
}

/**
 * 将GET或POST的数据自动转为可以插入数据库的字符
 * @param            $string
 * @param bool|false $is_ms
 *
 * @return mixed
 */
function daddslashes($string, $is_ms = false) {
    if(is_array($string)) {
        foreach($string as $key => $val) {
            $string[$key] = daddslashes($val, $is_ms);
        }
    } else {
        if ($is_ms) {
            $string = str_replace("'", "''", $string);
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}

/**
 * 用BASE64编码可用于URL的字符串
 * @param $data
 *
 * @return string
 */
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

/**
 * 解码BASE64编码的URL字符串
 * @param $data
 *
 * @return string
 */
function base64url_decode($data) {
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

/**
 * 陀峰转下划线
 * @param $str
 *
 * @return string
 */
function hump2under($str) {
    $reg = '/[A-Z]{1}[a-z0-9]+/';
    preg_match_all($reg,$str,$matches,PREG_SET_ORDER);
    $arr = [];
    foreach ($matches as $match) {
        $arr[] = strtolower($match[0]);
    }
    return join('_',$arr);
}

/**
 * 下划线转陀峰
 * @param $str
 *
 * @return string
 */
function under2hump($str) {
    $arr = explode('_',$str);
    $out = '';
    foreach ($arr as $key) {
        $out .= ucfirst(strtolower($key));
    }
    return $out;
}

/**
 * 抛出一个可查看的异常
 * @param $any
 *
 * @throws Exception
 */
function ex_debug($any) {
    throw new Exception(var_export($any,true));
}

/**
 * 统一的API输出信息设置
 * @param bool       $status   是否成功
 * @param string     $msg      输出的错误信息
 * @param null|array $extra    括展的输出信息
 * @param bool|true  $is_json  是否为JSON输出
 *
 * @return array|string
 */
function api_result($status,$msg,$extra=null,$is_json=true) {
    $result = [
        'status'=>$status,
        'msg'=>$msg
    ];
    if (is_assoc($extra)) {
        $result = \CK\Util\Arr::mrg($result,$extra);
    }

    return $is_json ? json_encode($result) : $result;
}

/**
 * 统一的AJAX输出信息设置
 * @param bool       $status   是否成功
 * @param string     $msg      输出的错误信息
 * @param null|array $extra    括展的输出信息
 * @param bool|true  $is_json  是否为JSON输出
 */
function ajax_result($status,$msg,$extra=null,$is_json=true) {
    exit(api_result($status,$msg,$extra,$is_json));
}

/**
 * 剪裁字符串
 *
 * @param  string $string 要剪切的字符串
 * @param  number $length 要剪切的长度
 * @return string 返回剪切后的字符串
 */
function cutstr($string, $length) {
    if (is_utf8($string)) {
        $utf8 = true;
        $string = mb_convert_encoding($string,"GB2312","UTF-8");
    }
    $strcut = '';
    if(strlen($string) > $length) {
        for($i = 0; $i < $length -1; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
        if ($utf8) $strcut = mb_convert_encoding($strcut,"UTF-8","GB2312");
        return $strcut;
    } else {
        if ($utf8) $string = mb_convert_encoding($string,"UTF-8","GB2312");
        return $string;
    }
}

/**
 * 是否UTF-8的编码字符串
 *
 * @param string $string 要检查的字符串
 * @return bool 是否UTF8编码
 */
function is_utf8($string) {
    return preg_match('%^(?:
	         [\x09\x0A\x0D\x20-\x7E]            # ASCII
	       | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
	       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
	       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
	       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
	       |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
	       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
	       |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
	   )*$%xs', $string);
}

/**
 * 随机取出指定长度的字符串
 * @param int    $length
 * @param string $chars
 *
 * @return string
 */
function random_str($length,$chars="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") {
    $char_length = strlen($chars);
    $return_str = '';
    for ($i=0;$i<$length;$i++) {
        $return_str .= $chars[mt_rand(0, $char_length-1)];
    }
    return $return_str;
}

/**
 * 在字段串两则加入指定字符
 * @param $chr
 * @param $string
 *
 * @return string
 */
function str_fix($chr,$string) {
    return $chr.$string.$chr;
}